package com.sh.util;

/**
 * @Auther: sh
 * @Version 1.0
 * @Description: 链栈
 */
public class LinkStack<T> {
    Node<T> top = null;


    public boolean isEmpty() {
        return top == null;
    }

    /**
     * 入栈
     *
     * @return true表示入栈成功
     */
    public boolean push(T n) {
        Node<T> newNode = new Node<>(n);
        newNode.next = top;
        top = newNode;
        return true;
    }

    /**
     * 出栈
     *
     * @return true表示出栈成功
     */
    public T pop() {
        if (isEmpty()) {
            throw new RuntimeException("栈为空，无法出栈");
        }
        top = top.next;
        return top.n;
    }

    /**
     * 取栈顶元素
     * 注意：只是获取，并不需要减少栈中的元素
     */
    public T peek() {
        if (isEmpty()) {
            throw new RuntimeException("栈为空，没有元素");
        }
        return top.n;
    }

    /**
     * 获取栈中元素的个数
     *
     * @return
     */
    public int size() {
        int res = 0;
        Node<T> cur = top;
        while (cur != null) {
            cur = cur.next;
            res++;
        }
        return res;
    }

    /**
     * 展示栈中所有的元素
     * 注意：需要从栈顶开始展示
     */
    public void show() {
        if (isEmpty()) {
            System.out.println("栈为空");
            return;
        }
        Node<T> temp = top;
        while (temp != null) {
            System.out.print(temp + "\t");
            temp = temp.next;
        }
        System.out.println();
    }

    /**
     * 清空栈中元素
     */
    public boolean clear() {
        if (top == null) {
            return true;
        }
        Node current = top;//辅助遍历链表
        Node temp = top;//临时存储top的引用，防止链表断裂
        //切记先要将top设为null
        top = null;
        while (current.next != null) {//注意最后一个结点不需要设为空，不然会出现空指针异常
            temp = temp.next;
            current.next = null;
            current = temp;
        }
        return true;
    }


    static class Node<T> {
        Node next;
        public T n;

        public Node() {
        }

        public Node(T n) {
            this.n = n;
        }

        @Override
        public String toString() {
            return "[n=" + n + "]";
        }
    }
}

